package com.slofzx.nuoda.sso.service.impl;

import com.slofzx.nuoda.common.exception.ServiceException;
import com.slofzx.nuoda.sso.entity.SsoAppInfo;
import com.slofzx.nuoda.sso.dto.SsoAppInfoDTO;
import com.slofzx.nuoda.sso.vo.SsoAppInfoVO;
import com.slofzx.nuoda.sso.dao.SsoAppInfoDAO;
import com.slofzx.nuoda.sso.service.SsoAppInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import com.slofzx.nuoda.common.enums.CommonResultEnum;
import com.slofzx.nuoda.common.enums.ServiceResult;
import com.slofzx.nuoda.common.service.impl.BaseServiceImpl;
import org.springframework.stereotype.Service;
import org.apache.commons.lang3.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;
import java.util.regex.Pattern;

/**
 * 单点登录应用信息服务实现类
 *
 * @author nuoda
 * @since 2023-11-09 10:43:59
 */
@Service("ssoAppInfoService")
public class SsoAppInfoServiceImpl extends BaseServiceImpl implements SsoAppInfoService {
    @Autowired
    private SsoAppInfoDAO ssoAppInfoDAO;

    private static final String  IP_REX = "^((25[0-5]|2[0-4]\\d|[1]{1}\\d{1}\\d{1}|[1-9]{1}\\d{1}|\\d{1})($|(?!\\.$)\\.)){4}$";

    /**
     * 将数据表数据转换为返回数据类型
     *
     * @param entity 数据表对应类
     * @return 实例对象
     */
    protected SsoAppInfoVO parseEntity2VO(SsoAppInfo entity) {
        SsoAppInfoVO vo = new SsoAppInfoVO();
        vo.setId(entity.getId());
        vo.setName(entity.getName());
        vo.setSecret(entity.getSecret());
        vo.setAllowIps(entity.getAllowIps());
        vo.setDisabled(entity.isDisabled());
        vo.setRemark(entity.getRemark());
        vo.setCreateTime(entity.getCreateTime());
        vo.setCreateUser(entity.getCreateUser());
        return vo;
    }

    /**
     * 将数据传递类转换为数据表数据类
     *
     * @param dto 数据传递类实例
     * @return 实例对象
     */
    protected SsoAppInfo parseDTO2Entity(SsoAppInfoDTO dto) {
        SsoAppInfo entity = new SsoAppInfo();
        entity.setId(dto.getId());
        entity.setName(dto.getName());
        entity.setSecret(dto.getSecret());
        entity.setAllowIps(dto.getAllowIps());
        entity.setDisabled(dto.getDisabled());
        entity.setRemark(dto.getRemark());
        return entity;
    }

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public SsoAppInfoVO queryById(String id) {
        SsoAppInfo entity = this.ssoAppInfoDAO.selectById(id);
        if (entity == null) {
            return null;
        }
        return parseEntity2VO(entity);
    }

    /**
     * 查询多条数据
     *
     * @param dto 数据传递类实例对象
     * @return 对象列表
     */
    @Override
    public List<SsoAppInfoVO> queryList(SsoAppInfoDTO dto) {
        //mybatis-plus 写法示例
        //IPage<SsoAppInfo> pageResult = this.evaModelDAO.selectPage(new Page<>(dto.getPageNo(),dto.getPageSize()),null);
        //List<SsoAppInfo> dataList = pageResult.getRecords();
        //dto.setCount((int) pageResult.getTotal());
        List<SsoAppInfo> dataList = this.ssoAppInfoDAO.queryList(dto);
        if (null == dataList || dataList.isEmpty()) {
            return Collections.emptyList();
        }
        List<SsoAppInfoVO> resultList = new ArrayList(dataList.size());
        for (SsoAppInfo item : dataList) {
            SsoAppInfoVO vo = parseEntity2VO(item);
            resultList.add(vo);
        }
        // TODO 添加其他关联查询数据
        return resultList;
    }

    /**
     * 新增数据
     *
     * @param dto 实例对象
     * @return 操作结果
     */
    @Override
    public ServiceResult create(SsoAppInfoDTO dto) {
        checkNotNull(dto.getId(),"appId不允许为空");
        checkNotNull(dto.getName(),"应用名称不允许为空");
        checkNotNull(dto.getSecret(),"秘钥不允许为空");
        // 校验ip合法性
        checkIp(dto);
        final SsoAppInfo ssoAppInfo = this.ssoAppInfoDAO.selectById(dto.getId());
        if (Objects.nonNull(ssoAppInfo)) {
            throw new ServiceException("appId已存在，请重新输入","appId已存在，请重新输入",null);
        }
        // TODO 添加校验逻辑
        SsoAppInfo entity = parseDTO2Entity(dto);
        preInsert(entity);
        entity.setId(dto.getId());
        this.ssoAppInfoDAO.insert(entity);
        return CommonResultEnum.SUCCESS;
    }

    /**
     * 校验ip合法性
     * @param dto
     */
    private void checkIp(SsoAppInfoDTO dto) {
        if (StringUtils.isNotEmpty(dto.getAllowIps())) {
            final String[] split = dto.getAllowIps().split(",");
            for (String ip : split) {
                if (!Pattern.matches(IP_REX,ip)) {
                    throw new ServiceException("ip: "+ip+" 格式错误不合规，请重新输入",ip+" 格式错误不合规，请重新输入",null);
                }
            }
        }
    }

    /**
     * 修改数据
     *
     * @param dto 实例对象
     * @return 操作结果
     */
    @Override
    public ServiceResult update(SsoAppInfoDTO dto) {
        String id = dto.getId();
        if (StringUtils.isEmpty(id)) {
            return CommonResultEnum.NOT_EXIST;
        }
        checkIp(dto);
        SsoAppInfo entity = this.ssoAppInfoDAO.selectById(id);
        if (entity == null) {
            return CommonResultEnum.NOT_EXIST;
        }
        // TODO 添加其他校验逻辑，如数据权限

        entity.setName(dto.getName());
        entity.setSecret(dto.getSecret());
        entity.setAllowIps(dto.getAllowIps());
        entity.setDisabled(dto.getDisabled());
        entity.setRemark(dto.getRemark());
        this.ssoAppInfoDAO.updateById(entity);
        return CommonResultEnum.SUCCESS;
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 操作结果
     */
    @Override
    public ServiceResult deleteById(String id) {
        // TODO 添加校验逻辑，如数据权限
        this.ssoAppInfoDAO.deleteById(id);
        return CommonResultEnum.SUCCESS;
    }
    /**
     * 校验空值
     * @param value
     * @param errMsg
     */
    public static void checkNotNull(String value, String errMsg) {
        if (StringUtils.isNotEmpty(value)) {
            return;
        }
        throw new ServiceException(errMsg, errMsg, null);
    }

}
